package com.bootssm.controller;

import com.bootssm.entity.*;
import com.bootssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @className: UserController
 * @description: TODO 类描述
 * @author: Mr.Song
 * @date: 2024/01/09 16:11
 **/

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    @PostMapping("/login")
    public User loninByUsernameAndPasswordController(@RequestBody UserLogin userLogin ,Model model) {

        List<User> userList = userService.loninByUsernameAndPassword(userLogin);

        if (userList.size() > 0) {
            User u = userList.get(0);
            if (u != null) {


                return u;
                //  return userList;
            } else {
                return null;
            }
        }
        return null;

    }


    @PostMapping("findAllUser")
    public PageView<User> findAllUser(@RequestBody UserVO userVO) {
        Integer page = userVO.getPage();
        Integer start = (page - 1) * userVO.getSize();
        userVO.setStart(start);
        List<User> userList = userService.findAllUser(userVO);
        Integer count = userService.getCount(userVO);
        PageView<User> pageView = new PageView<>();
        pageView.setDataList(userList);
        pageView.setCount(count);
        return pageView;
    }

    @PostMapping("findUserByid")
    public User findUserByidController(@RequestBody User user){
        String userid= user.getUserid();
       User userlest = userService.findUserByid(userid);
       return userlest;

    }

    @PostMapping("addUser")
    public Result addUserController(@RequestBody User user) {
        try {
            userService.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "保存失败");
        }
        return new Result("200", "保存成功");
    }

@PostMapping("updateUser")
    public Result updateUserController(@RequestBody User user) {
        try {
            userService.updateUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("500", "修改失败");
        }
        return new Result("200", "修改成功");
    }


       @PostMapping("/deleteUserById")
        public Result deleteUserById(@RequestBody User user){
            String userid= user.getUserid();
            userService.deleteUserById(userid);
            return new Result("200","删除成功");
        }

}
